var util = require('../base/Util');
var express = require('express');
var router = express.Router();
//数据库操作对象
var DbOpt = require("../models/Dbopt");
// 菜式
var Cuisine = require("../models/Cuisine");
//材料
var Ingredient = require("../models/Ingredient");


var pageSize = 20;


router.get("/init", function (req, res) {
    var page = util.di(req.query.page, 1);
    var cuisinename = util.ds(req.query.cuisinename);
    var queryJson = {};
    var andArray = [];

    if (cuisinename != "") {
        var dateCondition = {};
        queryJson["name"] = cuisinename;
    }
    DbOpt.pagination(Cuisine,queryJson,page,pageSize,function (qinfo) {
        res.render("cuisine/cuisine", {
            cuisines: qinfo.docs,
            moment: require("moment"),
            total: qinfo.totalItems,
            page: qinfo.currentPage,
            cuisinename: cuisinename,
            totalPage: qinfo.totalPage
        });
    })
});


router.get("/addinit", function (req, res) {
    DbOpt.findAll(Ingredient,function(ingredients){
        res.render("cuisine/cuisine_add", {
            ingredients: ingredients
        });
    });
});

router.post("/add", function (req, res) {
    var remark = req.body.remark;
    var buyItems = req.body.buyItems;
    var addData = {};
    addData["name"] = req.body.cuisinename;
    addData["productionMaterias"] = buyItems;
    addData["price"] = req.body.price;
    addData["time"] = new Date();
    DbOpt.addOne(Cuisine,addData,function(){
        res.json({success: 1});
    });
});

router.post("/update", function (req, res) {
    var buyItems = req.body.buyItems;
    var addData = {};
    addData["name"] = req.body.cuisinename;
    addData["productionMaterias"] = buyItems;
    addData["price"] = req.body.price;
    addData["time"] = new Date();
    var i = 0;

    var id = req.body.id;
    DbOpt.updateOneByID(Cuisine,id,addData,function(){
        res.json({success: 1});
    });
});


router.get("/editinit", function (req, res) {
    var id = req.query.id;
    DbOpt.findAll(Ingredient,function(ingredients){
        DbOpt.findOne(Cuisine,id,function(cuisines){
            res.render("cuisine/cuisine_edit", {
                ingredients: ingredients,
                cuisines: cuisines
            });
        });
    });
});
router.get("/del", function (req, res) {
    var id = req.query.id;
    DbOpt.del(Cuisine,id,function(){
        res.redirect('/cuisine/init');
    });
});


module.exports = router;